//引入样式
require("../../assets/fonts/iconfont.css");
require("../../assets/css/normalize.css");
require("../../assets/css/reset.css");
require("../../assets/fontst/iconfont.css");
require("../../assets/fonts/iconfont.css");
require("./sports_running.less");

//引入模块
const dom = require("../../utils/dom");
const axios = require("../../utils/axios");
const date = require("../../utils/date.js");
document.addEventListener("DOMContentLoaded", function () {
	// 高德定位 c43940ecac707bf75c64997740c68c4f

	AMap.plugin("AMap.Geolocation", function () {
		var geolocation = new AMap.Geolocation({
			enableHighAccuracy: true, // 是否使用高精度定位，默认：true
			timeout: 10000, // 设置定位超时时间，默认：无穷大
			offset: [10, 20], // 定位按钮的停靠位置的偏移量
			zoomToAccuracy: true, //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
			position: "RB", //  定位按钮的排放位置,  RB表示右下
		});

		geolocation.getCurrentPosition(function (status, result) {
			if (status == "complete") {
				// onComplete(result);
				console.log("定位成功", result);
			} else {
				// onError(result);
				console.log("定位失败");
			}
		});
	});

	//2. 计算距离
	var p1 = [104.065751, 30.657453];
	var p2 = [116.397455, 39.909187];
	var dis = AMap.GeometryUtil.distance(p1, p2);

	// 3. 定时器模拟跑步数据
	let duration = 0; //持续时间
	let meter = 0; //总里程
	let calorie = 0; //卡路里
	let timer = null; //定时器标识

	//设置一个函数，用于启动定时器
	function start() {
		timer = setInterval(function () {
			//速度
			let speed = getRand(3, 7);
			dom.get("#speed").textContent = speed + "米/秒";

			//时间
			duration++;
			dom.get("#time").textContent = date.getHMS(duration);

			//里程
			meter += speed;
			dom.get("#mileageNum").textContent = (meter / 1000).toFixed(3);

			//卡路里
			calorie = 60 * (meter / 1000) * 1.036;
			dom.get("#calorie").textContent = calorie.toFixed(2);
		}, 1000);
	}
	start();

	// 获取两个整数之间的随机数;
	function getRand(min, max) {
		return Math.floor(Math.random() * (max - min + 1)) + min;
	}
	// 暂停按钮;
	dom.get("#pause").addEventListener("click", function () {
		this.style.display = "none";
		dom.get("#play").style.display = "block";
		dom.get("#end").style.display = "block";
		clearInterval(timer); //清除定时器标识，停止计时
	});
	// 播放按钮
	dom.get("#play").addEventListener("click", function () {
		this.style.display = "none";
		dom.get("#pause").style.display = "block";
		dom.get("#end").style.display = "none";
		start(); //继续执行定时器
	});
	// 结束按钮
	dom.get("#end").addEventListener("click", function () {
		//发请求保存数据
		axios
			.post("/api/exercise/save", {
				type: 0,
				duration,
				calorie,
				meter,
			})
			.then((res) => {
				if (res.data.errno === 0) {
					alert("跑步结束，下次再跑...");
					location.href = "sports_run.html";
				}
			});
	});
});
